<?php

class ProductController extends MainController implements ControllerInterface {

    //o - order
    //v - order vector
    //t - total items to select
    public $tableConfig = array(
        'product_table_main' => array(
            'o' => array(
                'id' => 'product.id_product',
                'serial' => 'product.code',
                'name' => 'product_description.name',
                'count' => 'count',
                '_' => 'id'
            ),
            'v' => 'malejaco',
            't' => 10
        ),
        'infopts_table' => array(
            'o' => array(
                'id' => 'image_map.id_image_map',
                'name' => 'image_map_description.title',
                '_' => 'id'
            ),
            'v' => 'malejaco',
            't' => 10
        )
    );

    public function preDispatch($param) {
        $this->Run($param);
        $this->RunShared('Auth', array());
        $this->smarty->assign('param_from_url', $param);
        $this->smarty->assign('languages', LanguageDAL::GetResult(LanguageDAL::GetDalDataobj(array('sortBy' => 'id_language ASC', 'condition' => array('active' => '1')))));
        $this->smarty->assign('manufacturers', ManufacturerDAL::GetResult(ManufacturerDAL::GetDalDataObj(array('sortBy' => 'name ASC', 'condition' => array('active' => array('value' => 1))))));
        $this->smarty->assign('categories', CategoryDAL::getAdminCategoryTree());
    }

    public function postDispatch($param) {
        
    }

    public function IndexAction($param) {
//		Utils::ArrayDisplay($this->tableParams['product_table']);
        $lang = Registry::Get('default_language_id');
        $dal = ProductDAL::GetDalDataObj(array(
                    'tableData' => $this->tableParams['product_table_main'],
                    'join' => array(
                        'ProductDescription' => ' LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = ' . Registry::Get('default_language_id') . ')'
                    )
                ));

        if (Request::IsPost() && Request::Check('id_manufacturer')) {
            $data = Request::GetAllPost();
            SessionProxy::SetValue('product_filter', serialize($data));
            $this->addRedirect(Router::GenerateUrl('productIndex', array('product' => 'index')), 0);
        }

        if (SessionProxy::IsSetValue('product_filter')) {
            $data = SessionProxy::GetValue('product_filter');
            $data = unserialize($data);

            $filtering = false;

            if ($data['id_manufacturer'] > 0) {
                $dal->addCondition('id_manufacturer', $data['id_manufacturer']);
                $filtering = true;
            }

            if ($data['id_category'] > 0) {
                $dal->addCondition('id_category', $data['id_category']);
                $filtering = true;
            }

            if (strlen($data['code']) > 0) {
                $dal->addCondition('code', $data['code']);
                $filtering = true;
            }

            if (strlen($data['name']) > 0) {
                $dal->addCondition('product_description.name', "'%" . $data['name'] . "%'", 'LIKE');
                $filtering = true;
            }

            if ($filtering) {
                $this->smarty->assign('filter', $data);
            } else {
                SessionProxy::ClearValue('product_filter');
            }
        }

        $list = ProductDAL::GetResult($dal);
        $dal->setCount(true);
        $dal->setLimit('');
        $count = ProductDAL::GetResult($dal);

        $this->smarty->assign('list', $list);
        $this->smarty->assign('c', $count);
    }

    public function PhotoAction($param) {
        
    }

    public function AddAction($param) {
        $this->AddDescription('');
        $this->AddTitle(' ');

        $dal = ProductDAL::GetDalDataObj(array(
                    //'tableData' => $this->tableParams['product_table_main'],
                    'join' => array(
                        'ProductDescription' => ' LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = ' . Registry::Get('default_language_id') . ')'
                    )
                ));
        $this->smarty->assign('products', ProductDAL::GetResult($dal));


        if (Request::IsPost()) {

            //var_dump($_POST);
            //die();
            $data = Request::GetAllPost();
            if (isset($data['id_product'])) {
                $product = new ProductShop();
                $product->setIdProduct($data['id_product']);
                $product->setActive($data['active']);
                $product->setPrice($data['price']);
                $product->setIdShop(1);
                $product->setUrl($data['url']);
                $dalObj = ProductShopDAL::GetDalDataObj();
                $dalObj->setObj($product);
                $id_product = ProductShopDAL::Save($dalObj);
            }

            if (isset($data['name']) && is_array($data['name'])) {
                foreach (array_keys($data['name']) AS $id_language) {
                    $productDescription = new ProductShopDescription();
                    $productDescription->setIdProductShop($id_product);
                    $productDescription->setIdLanguage($id_language);
                    //$productDescription->setDescription(Request::GetPost('description_'.$id_language,false));
                    //$productDescription->setTechnologies(Request::GetPost('technologies_'.$id_language,false));
                    $productDescription->setName($data['name'][$id_language]);
                    //$productDescription->setSeoKeywords($data['seo_keywords'][$id_language]);
                    //$productDescription->setSeoDescription($data['seo_description'][$id_language]);
                    ProductShopDescriptionDAL::Insert($productDescription->getDalDataObj());
                }
            }

            $this->addRedirect(Router::GenerateUrl('', array('Index' => 'Products')), 0);
        }
    }

    public function EditAction($param) {
        $this->AddDescription('');
        $this->AddTitle(' ');
        $product = ProductShopDAL::GetResult(ProductShopDAL::GetDalDataobj(array('condition' => array(
                                'id_product_shop' => array($param['id'])
                                ))));
        $product = $product[0];

        //var_dump($product);

        $dal = ProductDAL::GetDalDataObj(array(
                    //'tableData' => $this->tableParams['product_table_main'],
                    'join' => array(
                        'ProductDescription' => ' LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = ' . Registry::Get('default_language_id') . ')'
                    )
                ));
        $this->smarty->assign('products', ProductDAL::GetResult($dal));

        $this->view->obj = $product;

        if (Request::IsPost()) {

            $data = Request::GetAllPost();
            if (isset($data['id_product'])) {
                //$product = new ProductShop();
                $product->setIdProduct($data['id_product']);
                $product->setActive($data['active']);
                $product->setPrice($data['price']);
                $product->setIdShop(1);
                $product->setUrl($data['url']);
                $dalObj = ProductShopDAL::GetDalDataObj();
                $dalObj->setObj($product);
                $id_product = ProductShopDAL::Save($dalObj);
            }

            if (isset($data['name']) && is_array($data['name'])) {
                foreach (array_keys($data['name']) AS $id_language) {
                    $productDescription = $product->getDescription($id_language);
                    $productDescription->setIdProductShop($id_product);
                    $productDescription->setIdLanguage($id_language);
                    //$productDescription->setDescription(Request::GetPost('description_'.$id_language,false));
                    //$productDescription->setTechnologies(Request::GetPost('technologies_'.$id_language,false));
                    $productDescription->setName($data['name'][$id_language]);
                    //$productDescription->setSeoKeywords($data['seo_keywords'][$id_language]);
                    //$productDescription->setSeoDescription($data['seo_description'][$id_language]);
                    ProductShopDescriptionDAL::Update($productDescription->getDalDataObj());
                }
            }

            $this->addRedirectInfo('Zmiany zostały zapisane', 'ok', Router::GenerateUrl('', array('Index' => 'Products')), 0);
        }



        $this->smarty->assign('obj', $product);
    }

    public function InfoptsAction($param) {
        $this->addScript('infopts.js');
        $obj = ProductDAL::GetResult(ProductDAL::GetDalDataObj(array(
                            'condition' => array(
                                'id_product' => array($param['id'])
                            )
                        )));
        $this->smarty->assign('obj', $obj[0]);

        if (!is_file(PATH_STATIC_CONTENT . '' . $obj[0]->getMainImage())) {
            $this->addRedirectInfo('Aby edytować info-punkty najpierw musisz wgrać obraz.', 'error', Router::GenerateUrl('productIndex', array('Product' => 'Index')));
            return;
        }

        if (Request::IsPost() && Request::Check('addPoint')) {
            $this->smarty->assign('x', Request::GetPost('x'));
            $this->smarty->assign('y', Request::GetPost('y'));
            $this->smarty->assign('h', Request::GetPost('h'));
            $this->smarty->assign('w', Request::GetPost('w'));
            $this->smarty->assign('addNew', 1);
        } else {
            if (Request::isPost() && Request::Check('confirmAdd')) {
                $imageMap = new ImageMap();
                $imageMap->setIdProduct($param['id']);
                $imageMap->setX(Request::GetPost('x'));
                $imageMap->setY(Request::GetPost('y'));
                $imageMap->setH(Request::GetPost('h'));
                $imageMap->setW(Request::GetPost('w'));
                $imageMap->setActive(Request::GetPost('active'));

                $id = ImageMapDAL::Insert($imageMap->getDalDataObj());

                $data = Request::GetAllPost();

                if (isset($data['name']) && is_array($data['name'])) {
                    foreach (array_keys($data['name']) AS $id_language) {
                        $productDescription = new ImageMapDescription();
                        $productDescription->setIdLanguage($id_language);
                        $productDescription->setDescription(Request::GetPost('description_' . $id_language, false, false));
                        $productDescription->setTitle($data['name'][$id_language]);
                        $productDescription->setIdImageMap($id);
                        ImageMapDescriptionDAL::Save($productDescription->getDalDataObj());
                    }
                }
                $this->addRedirect(Router::generateurl('productInfopts', array('product' => 'infopts', 'id' => $param['id'])), 0);
            }

            $lang = Registry::Get('default_language_id');
            $list = ImageMapDAL::GetResult(ImageMapDAL::GetDalDataObj(array(
                                'condition' => array(
                                    'id_product' => array($param['id'])
                                ),
                                'tableData' => $this->tableParams['infopts_table'],
                                'join' => array(
                                    'ImageMapDescription' => ' LEFT JOIN image_map_description ON(image_map.id_image_map = image_map_description.id_image_map AND image_map_description.id_language = ' . Registry::Get('default_language_id') . ')'
                                )
                            )));
            $count = ImageMapDAL::GetResult(ImageMapDAL::GetDalDataObj(array(
                                'condition' => array(
                                    'id_product' => array($param['id'])
                                ),
                                'count' => true
                            )));

            $this->smarty->assign('list', $list);
            $this->smarty->assign('c', $count);
        }
    }

    public function RemoveAction($param) {
        $this->setNoRender();
        $imageMap = ProductShopDAL::GetResult(ProductShopDAL::GetDalDataObj(array('condition' => array('id_product_shop' => array($param['id']), 'id_shop' => array('1')))));

        $id = 0;

        foreach ($imageMap AS $item) {

            ProductShopDAL::Delete($item->getDalDataObj());
        }

        $this->addRedirect(Router::Generateurl('', array('Index' => 'Products')), 0);
    }

    public function StatsAction($param) {
        $this->AddDescription('');
        $this->AddTitle(' ');

        $dates[] = array('value' => date("Y-m-d"), 'cond' => ' = ', 'c' => '1', 'group' => 'HOUR');
        $dates[] = array('value' => date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y"))), 'cond' => ' = ', 'c' => '1', 'group' => 'HOUR');
        $dates[] = array('value' => '"' . date('Y-m') . '%"', 'cond' => ' LIKE ', 'c' => (24 * 30), 'group' => 'DAY');
        $dates[] = array('value' => '"' . date('Y-m', mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'))) . '%"', 'cond' => ' LIKE ', 'c' => (24 * 30), 'group' => 'DAY');
        $dates[] = array('value' => '', 'cond' => '', 'c' => (24 * 30), 'group' => 'MONTH');

        $dal2 = ProductStatDAL::GetDalDataObj();
        $dal2->addCondition('product_stat.id_shop', Registry::Get('shopObj')->getId());
        $dal2->addSelectFields('count', 'count(product_stat.id_product)');



        $dal = ProductDAL::GetDalDataObj(array(
                    'tableData' => $this->tableParams['product_table_main'],
                    'join' => array(
                        'ProductDescription' => ' LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = ' . Registry::Get('default_language_id') . ')',
                        'ProductStat' => ' LEFT JOIN product_stat ON (product.id_product = product_stat.id_product AND product_stat.id_shop=1)',
                        'ProductShop' => ' INNER JOIN product_shop ON(product.id_product = product_shop.id_product)'
                    )
                ));
        $dal->addSelectFields('count', 'count(product_stat.id_product)');
        $dal->setGroupBy('product.id_product');
        $dal->addCondition('product_shop.id_shop', Registry::Get('shopObj')->getId());

        if (Request::IsPost() && Request::Check('interval')) {
            $data = Request::GetAllPost();
            SessionProxy::SetValue('product_filter', serialize($data));
            $this->addRedirect(Router::GenerateUrl('', array('Product' => 'Stats')), 0);
        }

        if (SessionProxy::IsSetValue('product_filter')) {
            $data = SessionProxy::GetValue('product_filter');
            $data = unserialize($data);

            $filtering = false;

            if ($data['interval'] != '') {
                if (isset($dates[$data['interval']])) {
                    $cond = $dates[$data['interval']];
                    if ($cond['value'] != '') {
                        $dal->addCondition('product_stat.date', $cond['value'], $cond['cond']);
                        $dal2->addCondition('product_stat.date', $cond['value'], $cond['cond']);
                        $filtering = true;
                        $c = $cond['c'];
                        $this->smarty->assign('graphMin', date('Y-m-d', strtotime(date('Y', strtotime($cond['value'])).'-'.(date('m', strtotime($cond['value']))-1).'-'.date('d', strtotime($cond['value'])))));
                        $this->smarty->assign('graphMax', date('Y-m-d', strtotime(date('Y', strtotime($cond['value'])).'-'.(date('m', strtotime($cond['value']))-1).'-'.date('d', strtotime($cond['value'])))));
                        $setDates = true;
                    } else {
                        $c = $cond['c'];
                    }
                    $dal2->setGroupBy($cond['group'] . '(product_stat.date)');
                }
            }

            if ($filtering) {
                $this->smarty->assign('filter', $data);
            } else {
                SessionProxy::ClearValue('product_filter');
            }
        } else {
            $dal2->setGroupBy('DAY(product_stat.date)');
            $c = (30 * 24);
        }

        $dal2->setOrderBy('product_stat.date');


        $result = ProductStatDAL::GetResult($dal2);

        // dla generowania pustych danych do wykresu

$this->smarty->assign('g', 24);
$this->smarty->assign('gv', 30);
        if (isset($data['interval'])) {
            if ($data['interval'] == '0') {
                for($i=0;$i<25;$i++) {
                    $graph[$i] = 0;
                }
                
                $setDates = true;
                $this->smarty->assign('gv', 1);
                $this->smarty->assign('g', 1);
                if(isset($result) && count($result)>1) {
                $this->smarty->assign('graphMin', date("Y", strtotime($result[0]->getDate())).'-'.(date('m', strtotime($result[0]->getDate()))-1) . '-'.date('d', strtotime($result[0]->getDate())));
                $this->smarty->assign('graphMax', date("Y", strtotime($result[(count($result)-1)]->getDate())).'-'.(date('m', strtotime($result[(count($result)-1)]->getDate()))-1)  . '-'.date('d', strtotime($result[(count($result)-1)]->getDate())));
                }
            } elseif ($data['interval'] == '1') {
                for($i=0;$i<25;$i++) {
                    $graph[$i] = 0;
                }
                $setDates = true;
                $this->smarty->assign('gv', 1);
                $this->smarty->assign('g', 1);
            } elseif ($data['interval'] == '2') {
                $graph = $this->getDaysInBetween(date("Y-m") . '-01', date("Y-m") . '-'.$this->getLastDayofMonth(date('m'), date('Y')));
                $this->smarty->assign('graphMin', date("Y").'-'.(date('m')-1) . '-01');
                $this->smarty->assign('graphMax', date("Y").'-'.(date('m')-1)  . '-'.$this->getLastDayofMonth(date('m'), date('Y')));
                $setDates = true;
                $this->smarty->assign('gv', 1);
            } elseif ($data['interval'] == '3') {
                //echo $this->getLastDayofMonth(date('m'), date('Y'));    
                $graph = $this->getDaysInBetween(date("Y").'-'.(date('m')-1) . '-01', date("Y").'-'.(date('m')-1) . '-'.$this->getLastDayofMonth(date('m'), date('Y')));
                $this->smarty->assign('graphMin', date("Y").'-'.(date('m')-2) . '-01');
                $this->smarty->assign('graphMax', date("Y").'-'.(date('m')-2)  . '-'.$this->getLastDayofMonth(date('m'), date('Y')));
                $setDates = true;
                $this->smarty->assign('gv', 1);
                //echo count($graph);
            } else {//var_dump($result);
                if(isset($result) && count($result)>1) {
                $graph = $this->getDaysInBetween(date("Y", strtotime($result[0]->getDate())).'-'.(date('m', strtotime($result[0]->getDate()))-1) . '-'.date('d', strtotime($result[0]->getDate())), date("Y", strtotime($result[(count($result)-1)]->getDate())).'-'.(date('m', strtotime($result[(count($result)-1)]->getDate()))-1) . '-'.date('d', strtotime($result[(count($result)-1)]->getDate())));
                $this->smarty->assign('graphMin', date("Y", strtotime($result[0]->getDate())).'-'.(date('m', strtotime($result[0]->getDate()))-1) . '-'.date('d', strtotime($result[0]->getDate())));
                $this->smarty->assign('graphMax', date("Y", strtotime($result[(count($result)-1)]->getDate())).'-'.(date('m', strtotime($result[(count($result)-1)]->getDate()))-2)  . '-'.date('d', strtotime($result[(count($result)-1)]->getDate())));
                $setDates = true;}
                $this->smarty->assign('gv', 30);
            }
        }


        if (!isset($graph)) {
         
            if(isset($result) && count($result)>1) {
                $graph = $this->getDaysInBetween(date("Y", strtotime($result[0]->getDate())).'-'.(date('m', strtotime($result[0]->getDate()))) . '-'.date('d', strtotime($result[0]->getDate())), date("Y", strtotime($result[(count($result)-1)]->getDate())).'-'.(date('m', strtotime($result[(count($result)-1)]->getDate()))) . '-'.date('d', strtotime($result[(count($result)-1)]->getDate())));
                //var_dump($graph);
                $this->smarty->assign('graphMin', date("Y", strtotime($result[0]->getDate())).'-'.(date('m', strtotime($result[0]->getDate()))-1) . '-'.date('d', strtotime($result[0]->getDate())));
                $this->smarty->assign('graphMax', date("Y", strtotime($result[(count($result)-1)]->getDate())).'-'.(date('m', strtotime($result[(count($result)-1)]->getDate()))-2)  . '-'.date('d', strtotime($result[(count($result)-1)]->getDate())));
                $setDates = true;}
                $this->smarty->assign('gv', 1);
            
        }

        $dates = null;

        foreach ($result as $row) {
            //if (count($graph) == 0) {
                $graph[date('Y-m-d', strtotime($row->getDate()))] = $row->getCount();
            //    $dates = $row->getDate();
           /* } else {
                //var_dump($dates);
                $t1 = strtotime($dates);

                $t2 = strtotime($row->getDate());
                //echo $dates; var_dump($t1);
                //echo $row->getDate(); var_dump($t2);
                //echo"<hr>";
                $dateDiff = ($t2 - $t1);
                //month
                //echo $c;
                $amount = (floor($dateDiff / (60 * 60 * $c)));
                //  $amount = ($amount/-1);
                echo intval($amount) . "<br />";
                if (intval($amount) > 1) {
                    for ($i = 1; $i < intval($amount); $i++) {
                        $graph[] = 0;
                    }
                }
                $graph[] = $row->getCount();
                $dates = $row->getDate();
            }*/
        }
        //var_dump($graph);
        $this->smarty->assign('graph', $graph);
        if (count($result) > 0 && !isset($setDates)) {
            $datestring = strtotime($result[0]->getDate());
            $this->smarty->assign('graphMin', date('Y-m-d h:i:s', mktime(date('h', $datestring), (date('m', $datestring)-1), date('s', $datestring), date('m', $datestring) - 1, date('d', $datestring), date('Y', $datestring))));
            $this->smarty->assign('graphMax', $result[count($result) - 1]->getDate());
        }

        $list = ProductDAL::GetResult($dal);
        $dal->setCount(true);
        $dal->setLimit('');
        $count = ProductDAL::GetResult($dal);

        $this->smarty->assign('list', $list);
        $this->smarty->assign('c', $count);
    }

    private function getDaysInBetween($start, $end) {
        // Vars  
        $day = 86400; // Day in seconds  
        $format = 'Y-m-d'; // Output format (see PHP date funciton)  
        $sTime = strtotime($start); // Start as time  
        $eTime = strtotime($end); // End as time  
        $numDays = round(($eTime - $sTime) / $day) + 1;
        $days = array();

        // Get days  
        for ($d = 0; $d < $numDays; $d++) {
            $days[date($format, ($sTime + ($d * $day)))] = 0;
        }

        // Return days  
        return $days;
    }

    private function getLastDayofMonth($month, $year) {
        return idate('d', mktime(0, 0, 0, ($month + 1), 0, $year));
    }

    public function InfoptsRemoveAction($param) {
        $this->setNoRender();
        $imageMap = ImageMapDAL::GetResult(ImageMapDAL::GetDalDataObj(array('condition' => array('id_image_map' => array($param['id'])))));

        $id = 0;

        foreach ($imageMap AS $item) {
            $id = $item->getIdProduct();

            ImageMapDAL::Delete($item->getDalDataObj());
        }

        $this->addRedirect(Router::Generateurl('productInfopts', array('product' => 'infopts', 'id' => $id)), 0);
    }

    public function InfoptsEditAction($param) {
        $this->addScript('infopts.js');
        $this->partialTemplate = 'InfoptsEdit.tpl';
        $map = ImageMapDAL::GetResult(ImageMapDAL::GetDalDataObj(array('condition' => array('id_image_map' => array($param['id'])))));
        $obj = ProductDAL::GetResult(ProductDAL::GetDalDataObj(array('condition' => array('id_product' => array($map[0]->getIdProduct())))));


        if (Request::isPost() && Request::Check('confirmAdd')) {
            $imageMap = $map[0];
            //$imageMap->setIdProduct($param['id']);
            $imageMap->setX(Request::GetPost('x'));
            $imageMap->setY(Request::GetPost('y'));
            $imageMap->setH(Request::GetPost('h'));
            $imageMap->setW(Request::GetPost('w'));
            $imageMap->setActive(Request::GetPost('active'));

            $id = ImageMapDAL::Save($imageMap->getDalDataObj());

            $data = Request::GetAllPost();

            if (isset($data['title']) && is_array($data['title'])) {
                foreach (array_keys($data['title']) AS $id_language) {
                    $productDescription = $imageMap->getDescription($id_language);
                    $productDescription->setIdLanguage($id_language);
                    $productDescription->setDescription(Request::GetPost('description_' . $id_language, false, false));
                    $productDescription->setTitle($data['title'][$id_language]);
                    ImageMapDescriptionDAL::Save($productDescription->getDalDataObj());
                }
            }
            $this->addRedirect(Router::generateurl('productInfopts', array('product' => 'infopts', 'id' => $obj[0]->getId())), 0);
        }


        $this->smarty->assign('map', $map[0]);
        $this->smarty->assign('obj', $obj[0]);
    }

}

